package com.kedll.library.adapter;

import android.content.Context;
import android.widget.ArrayAdapter;

import com.kedll.library.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 多选列表适配器
 * Created by QiQi on 15/4/19.
 */
public abstract class MultipleChoiceModeAdapter<T> extends MyArrayAdapter<T> {

    private List<Boolean> isSelected;

    /**
     * 构造函数
     * @param context
     */
    public MultipleChoiceModeAdapter(Context context) {
        super(context, 0);
        isSelected = new ArrayList<>();
    }

    /**
     * 添加列表数据
     * @param ones
     */
    public void addAll(List ones) {
        if (CollectionUtils.isNotEmpty(ones)) {
            int i = getCount();
            int size = getCount() + ones.size();
            for (; i < size; i++) {
                isSelected.add(i, false);
            }
        }
        super.addAll(ones);
    }

    public void toggle(int position) {
        boolean selected = isSelected.get(position);
        isSelected.set(position, !selected);
        notifyDataSetChanged();
    }

    /**
     * 全选
     * @return
     */
    public boolean selectAll() {
        if (isSelected != null) {
            for (int i = 0; i < isSelected.size(); i++) {
                isSelected.set(i, true);
            }
            notifyDataSetChanged();
            return true;
        }
        return false;
    }

    /**
     * 取消全选
     * @return
     */
    public boolean unSelectAll() {
        if (isSelected != null) {
            for (int i = 0; i < isSelected.size(); i++) {
                isSelected.set(i, false);
            }
            notifyDataSetChanged();
            return true;
        }
        return false;
    }

    /**
     * 返回选中的数据
     * @return
     */
    public List getSelectItems() {
        List selectItems = new ArrayList();
        for(int i = 0; i < isSelected.size(); i++){
            if(isSelected.get(i)){
                selectItems.add(getItem(i));
            }
        }
        return  selectItems;
    }

    @Override
    public void clear() {
        isSelected.clear();
        super.clear();
    }
}
